package conf

import (
	"fmt"
	"sync"

	"github.com/gin-gonic/gin"
)

type application struct {
	Host   string `json:"host" yaml:"host"`
	Port   int    `json:"port" yaml:"port"`
	Domain string `json:"domain" yaml:"domain"`

	server *gin.Engine
	lock   sync.Mutex
	root   gin.IRouter
}

func Application() *application {
	return &application{
		Host: "0.0.0.0",
		Port: 9999,
	}
}

func (a *application) GinServer() *gin.Engine {
	a.lock.Lock()
	defer a.lock.Unlock()

	if a.server == nil {
		a.server = gin.New()
	}
	return a.server
}

func (a *application) GinRootRouter() gin.IRouter {
	r := a.GinServer()
	if a.root == nil {
		a.root = r.Group("arm").Group("api").Group("v1")
	}
	return a.root
}

func (a *application) Address() string {
	return fmt.Sprintf("%s:%d", a.Host, a.Port)
}

func (a *application) Start() error {
	return a.GinServer().Run(a.Address())
}
